<?php
/*
*Auth: Wolix li
*Mail: wenmingpig@gmail.com
*MSN: wenbmingpig@msn.com
*WebSite: http://www.wolix.com
*Date:
*/
define("HTTP_SESSION_STARTED",      1);
define("HTTP_SESSION_CONTINUED",    2);
class SessData extends Think
{//类定义开始
    /**
     * Security checking level
     *
     * Possible value:
     *    0 - no check;
     *    1 - check browser characteristics (HTTP_USER_AGENT/HTTP_ACCEPT_LANGUAGE), to be implemented in the future now;
     *    2 - check browser and IP A.B;
     *    3 - check browser and IP A.B.C, recommended;
     *    4 - check browser and IP A.B.C.D;
     *
     * @var    int
     * @access    public
     */
    var $securityLevel = 3;

    /**
     * Enable regenerate_id
     *
     * @var    bool
     * @access    public
     */
    var $enableRegenerateId = false;
    /**
     * Open a session
     *
     * @param    string  $save_path
     * @param    string  $session_name
     *
     * @return    bool
     */
    function open($save_path, $session_name)
    {
        return true;
    }
    /**
     * Close a session
     *
     * @return    bool
     */
    function close()
    {
        self::gc_force();
        return true;
    }
    /**
     * Read a session from the database
     *
     * @param    string  &sess_id    ID of the session
     *
     * @return    array   Session data
     */
    function read($sess_id)
    {
    	$sData = M('session')->field('sess_data', 'sess_ip')->where("sess_id='".$sess_id."'")->find();
    	if($sData){
			/*
            if ($this->securityLevel > 1) {
                $pos = strpos($sData['sess_ip'], ".", $this->securityLevel - 1);
                if (strncmp($sData['sess_ip'], $_SERVER['REMOTE_ADDR'], $pos)) {
                   $sData['sess_data'] = '';
                }
            }*/
            return $sData['sess_data'];
    	}
        return '';
    }
    /**
     * Write a session to the database
     *
     * @param   string  $sess_id
     * @param   string  $sess_data
     *
     * @return  bool
     **/
    function write($sess_id, $sess_data)
    {
    	$data = array(
			'sess_id' => $sess_id,
    		'sess_updated' => time(),
    		'sess_data' => serialize($sess_data),
    		);
		$dao = M('session');
		    	$sData = M('session')->field('sess_data', 'sess_ip')->where("sess_id='".$sess_id."'")->find();
 			F('sess'.time(),$dao);

		//$r = $dao->data($data)->save();
		if(!$r){
			$r = $dao->data($data)->add();
 			F('sess'.time(),$dao);

		}

/*
    	if(!$dao->where("sess_id = '".$sess_id."'")->data($data)->save()){
    		$data['sess_id'] = empty($sess_id)?session_id():$sess_id;
    		$data['sess_ip'] = $_SERVER['REMOTE_ADDR'];
	   $sql = "INSERT INTO sh_session (sess_id,sess_updated,sess_ip,sess_data) VALUES ('".$sess_id."','".time()."','".$data['sess_ip']."','".serialize($sess_data)."')";

		$r= $dao->execute($sql);

		}
		*/
        return true;
    }

    /* Destroy a session
     *
     * @param   string  $sess_id
     *
     * @return  bool
     **/
    function destroy($sess_id)
    {
       return  M('session')->where("sess_id = '".$sess_id."'")->delete();
    }

    /**
     * Garbage Collector
     *
     * @param   int $expire Time in seconds until a session expires
     * @return  bool
     **/
    function gc($expire)
    {
        if (empty($expire)) {
            return true;
        }
        $mintime = time() - intval($expire);
        return M('session')->where("sess_updated < ".$mintime."")->delete();
    }
    /**
     * Force gc for situations where gc is registered but not executed
     **/
    function gc_force()
    {
        if (rand(1, 100) < 11) {
            $expire = @ini_get('session.gc_maxlifetime');
            $expire = ($expire > 0) ? $expire : 900;
            self::gc($expire);
        }
    }
    /**
     * Update the current session id with a newly generated one
     *
     * To be refactored
     *
     * @param   bool $delete_old_session
     * @return  bool
     **/
    function regenerate_id($delete_old_session = false)
    {
        $phpversion = phpversion();

        if (!$this->enableRegenerateId) {
            $success = true;

        // parameter "delete_old_session" only available as of PHP 5.1.0
        } else if (version_compare($phpversion, "5.1.0", ">=")) {
            $success = session_regenerate_id($delete_old_session);

        } else {
            $old_session_id = session_id();
            // session_regenerate_id function available as of PHP 4.3.2
            if (function_exists("session_regenerate_id")) {
                $success = session_regenerate_id();
                if ($success && $delete_old_session) {
                    // Extra step to destroy old session
                    self::destroy($old_session_id);
                }
                // For PHP prior to 4.3.2
            } else {
                // session_regenerate_id is not defined, create new session ID
                $session_id = md5(uniqid(rand(), true) . @$_SERVER['HTTP_USER_AGENT']);
                // Set the new session ID
                session_id($session_id);
                // Destory old session on request
                if ($delete_old_session) {
                    self::destroy($old_session_id);
                    // switch old session to new one
                } else {
                	$data['sess_id'] = $session_id;
                	M('session')->where("sess_id = '".$old_session_id."'")->data($data)->save();
                }
                $success = true;
            }
        }

        // Force updating cookie for session cookie is not issued correctly in some IE versions or not automatically issued prior to PHP 4.3.3 for all browsers
        if ($success) {
            self::update_cookie();
        }

        return $success;
    }
    /**
     * Update cookie status for current session
     *
     * To be refactored
     * FIXME: how about $xoopsConfig['use_ssl'] is enabled?
     *
     * @param   string  $sess_id    session ID
     * @param   int     $expire     Time in seconds until a session expires
     * @return  bool
     **/
    function update_cookie($sess_id = null, $expire = null)
    {
        $session_name = (C('use_mysession') && C('session_name') != '') ? C('session_name'): session_name();
        $session_expire = !is_null($expire) ? intval($expire) : ((C('use_mysession') && C('session_name') != '') ? C('session_expire') * 60 : ini_get("session.cookie_lifetime"));
        $session_id = empty($sess_id) ? session_id() : $sess_id;
        setcookie($session_name, $session_id, $session_expire ? time() + $session_expire : 0, '/', C('COOKIE_DOMAIN'), 0);
    }
}
?>